<template>
  <div class="add-death-record-form">
    <a-form :model="form" :rules="rules" ref="formRef" layout="vertical">
      <a-form-item label="选择人员" name="lifeRecordId">
        <a-select v-model:value="form.lifeRecordId" placeholder="选择要登记死亡的人员" show-search :filter-option="filterOption" @change="handlePersonSelect">
          <a-select-option v-for="person in alivePersons" :key="person.id" :value="person.id"> {{ person.name }} - {{ person.location }} ({{ person.currentAge }}岁) </a-select-option>
        </a-select>
      </a-form-item>

      <div v-if="selectedPerson" class="selected-person">
        <a-descriptions :column="2" size="small" bordered>
          <a-descriptions-item label="姓名">{{ selectedPerson.name }}</a-descriptions-item>
          <a-descriptions-item label="年龄">{{ selectedPerson.currentAge }}岁</a-descriptions-item>
          <a-descriptions-item label="天定寿命">{{ selectedPerson.destinedLifespan }}岁</a-descriptions-item>
          <a-descriptions-item label="居住地">{{ selectedPerson.location }}</a-descriptions-item>
        </a-descriptions>
      </div>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="死亡日期" name="deathDate">
            <a-date-picker v-model:value="form.deathDate" placeholder="选择死亡日期" style="width: 100%" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="死亡时间" name="deathTime">
            <a-time-picker v-model:value="form.deathTime" placeholder="选择死亡时间" format="HH:mm" style="width: 100%" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="死亡地点" name="deathLocation">
        <a-input v-model:value="form.deathLocation" placeholder="请输入死亡地点" />
      </a-form-item>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="死因分类" name="deathCause">
            <a-select v-model:value="form.deathCause" placeholder="选择死因分类" @change="handleCauseChange">
              <a-select-option v-for="(cause, key) in deathCauses" :key="key" :value="key">
                {{ cause.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="具体死因" name="specificCause">
            <a-select v-model:value="form.specificCause" placeholder="选择具体死因" :disabled="!form.deathCause">
              <a-select-option v-for="subcategory in deathCauses[form.deathCause]?.subcategories || []" :key="subcategory" :value="subcategory">
                {{ subcategory }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="目击者人数" name="witnesses">
            <a-input-number v-model:value="form.witnesses" :min="0" :max="100" style="width: 100%" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="报告人" name="reportedBy">
            <a-input v-model:value="form.reportedBy" placeholder="请输入报告人" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="遗言内容">
        <a-textarea v-model:value="form.lastWords" placeholder="请记录逝者的遗言" :rows="3" />
      </a-form-item>

      <a-form-item label="备注">
        <a-textarea v-model:value="form.notes" placeholder="请输入备注信息" :rows="2" />
      </a-form-item>

      <a-form-item>
        <a-space>
          <a-button type="primary" @click="handleSubmit" :loading="submitting"> 提交登记 </a-button>
          <a-button @click="handleCancel"> 取消 </a-button>
          <a-button @click="handleReset"> 重置 </a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { message } from 'ant-design-vue'
import { useLifeDeathStore } from '@/stores/lifeDeath'

const emit = defineEmits(['success', 'cancel'])

const lifeDeathStore = useLifeDeathStore()
const formRef = ref()
const submitting = ref(false)
const selectedPerson = ref(null)

const form = reactive({
  lifeRecordId: null,
  deathDate: null,
  deathTime: null,
  deathLocation: '',
  deathCause: '',
  specificCause: '',
  witnesses: 1,
  reportedBy: '家属',
  lastWords: '',
  notes: ''
})

const rules = {
  lifeRecordId: [{ required: true, message: '请选择人员' }],
  deathDate: [{ required: true, message: '请选择死亡日期' }],
  deathTime: [{ required: true, message: '请选择死亡时间' }],
  deathLocation: [{ required: true, message: '请输入死亡地点' }],
  deathCause: [{ required: true, message: '请选择死因分类' }],
  specificCause: [{ required: true, message: '请选择具体死因' }],
  witnesses: [{ required: true, message: '请输入目击者人数' }],
  reportedBy: [{ required: true, message: '请输入报告人' }]
}

const alivePersons = computed(() => lifeDeathStore.lifeRecords.filter((record) => record.status === 'alive'))

const deathCauses = computed(() => lifeDeathStore.deathCauses)

const filterOption = (input, option) => {
  return option.children[0].children.toLowerCase().includes(input.toLowerCase())
}

const handlePersonSelect = (id) => {
  selectedPerson.value = alivePersons.value.find((person) => person.id === id)
}

const handleCauseChange = () => {
  form.specificCause = ''
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitting.value = true

    const recordData = {
      ...form,
      deathDate: form.deathDate.format('YYYY-MM-DD'),
      deathTime: form.deathTime.format('HH:mm'),
      ageAtDeath: selectedPerson.value?.currentAge || 0,
      name: selectedPerson.value?.name || ''
    }

    await lifeDeathStore.addDeathRecord(recordData)
    emit('success')
  } catch (error) {
    if (error.message) {
      message.error(error.message)
    }
  } finally {
    submitting.value = false
  }
}

const handleCancel = () => {
  emit('cancel')
}

const handleReset = () => {
  formRef.value.resetFields()
  selectedPerson.value = null
}
</script>

<style lang="scss" scoped>
@use '@/styles/variables.scss' as *;

.add-death-record-form {
  padding: 16px;
  color: $text-primary;

  .selected-person {
    margin-top: 16px;
    padding: 16px;
    background: rgba(255, 255, 255, 0.05);
    border: 1px solid $border-color;
    border-radius: 8px;
    color: $text-primary;
  }
}
</style>
